<template>
  <div class="battery" :title="title">
    <svg :width="width" :height="height" viewBox="0 0 34 16" xmlns="http://www.w3.org/2000/svg">
      <!-- Body -->
      <rect x="1" y="3" width="28" height="10" rx="2" ry="2" class="outer" />
      <!-- Terminal -->
      <rect x="30" y="6" width="3" height="4" rx="1" class="outer" />
      <!-- Level Fill -->
      <clipPath id="battery-clip">
        <rect x="2" y="4" width="26" height="8" rx="1.5" />
      </clipPath>
      <rect x="2" y="4" :width="fillWidth" height="8" rx="1.5" class="fill" clip-path="url(#battery-clip)" />
      <!-- Charging bolt -->
      <path v-if="charging === true" class="bolt" d="M16 4 L12 10 H15 L14 14 L18 8 H15 Z" />
    </svg>
    <span v-if="percent !== null" class="text">{{ percent }}%</span>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useBattery } from '@vueuse/core'

const props = defineProps<{ size?: number }>()
const width = computed(() => props.size ?? 28)
const height = computed(() => Math.round((props.size ?? 28) * 0.55))

const { charging, level, unsupported } = useBattery()

const percent = computed(() => {
  if (level.value == null) return null
  const p = Math.round(level.value * 100)
  return Math.max(0, Math.min(100, p))
})

const fillWidth = computed(() => {
  const base = 26
  if (percent.value == null) return base
  return Math.max(2, Math.round((percent.value / 100) * base))
})

const title = computed(() => {
  if (unsupported.value) return '电池信息不可用'
  const p = percent.value != null ? `${percent.value}%` : '—'
  return charging.value ? `正在充电 · ${p}` : `未充电 · ${p}`
})
</script>

<style scoped>
.battery {
  display: inline-flex;
  align-items: center;
  gap: 6px;
}
.outer { stroke: currentColor; fill: none; stroke-width: 1.5; }
.fill { fill: currentColor; opacity: 0.7; }
.bolt { fill: currentColor; opacity: 0.9; }
.text { font-size: 12px; }
</style>


